package com.lancoo.ccas53.arrangecourse.entities;

import com.lancoo.ccas53.arrangecourse.common.BinaryUtil;
import com.lancoo.ccas53.pojo.dto.ArrangePeriod;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: liufeng
 * @CreateTime: 2024-12-17  09:54
 * @Description:
 */
public class ClassTimeCodeContext {
    private static final Map<String, Map<String,String>> CLASSTIMECODE = new HashMap<>();

    private static final ReentrantLock lock = new ReentrantLock();

    private static List<ArrangePeriod> timeCodeList;



    public static Map<String, Map<String,String>> get(){
        return CLASSTIMECODE;
    }

    public static Map<String,String> get(String classId){
        return CLASSTIMECODE.getOrDefault(classId,new HashMap<>());
    }

    public static String get(String classId, String timeCode){
        if (!CLASSTIMECODE.containsKey(classId)){
            return null;
        }
        return CLASSTIMECODE.get(classId).getOrDefault(timeCode,null);
    }

    public static void saveClassTimeCode(TeachingClassUnit teachingClassUnit) {
        String classIds = teachingClassUnit.getPhyClassId();
        if (cn.hutool.core.util.StrUtil.isNotEmpty(classIds)){
            lock.lock();
            try {
                for (TimeslotRoom timeslotRoom : teachingClassUnit.getTimeslotRoomList()) {
                    String timeCode = timeslotRoom.getTimeslotCode();
                    String week = timeslotRoom.getWeeks();
                    for (String classId : classIds.split(",")) {
                        put(classId, timeCode, week);
                    }
                }
            }finally {
                lock.unlock();
            }
        }
    }

    public static void saveClassTimeCodeList(LinkedList<TeachingClassUnit> teachingClassUnitLinkedList) {
        for (TeachingClassUnit teachingClassUnit : teachingClassUnitLinkedList) {
            saveClassTimeCode(teachingClassUnit);
        }
    }

    public static void put(String classId, String timeCode, String week){
        if (!CLASSTIMECODE.containsKey(classId)){
            Map<String,String> classMap = new HashMap<>();
            classMap.put(timeCode,week);
            CLASSTIMECODE.put(classId,classMap);
        }else {
            Map<String, String> classMap = CLASSTIMECODE.get(classId);
            if (!classMap.containsKey(timeCode)){
                classMap.put(timeCode,week);
            }else {
                classMap.put(timeCode, BinaryUtil.binaryOR(classMap.get(timeCode),week));
            }
            CLASSTIMECODE.put(classId,classMap);
        }

    }


    public static List<ArrangePeriod> getTimeCodeList() {
        return timeCodeList;
    }

    public static void setTimeCodeList(List<ArrangePeriod> timeCodeList) {
        ClassTimeCodeContext.timeCodeList = timeCodeList;
    }
}
